iT邦幫忙

2025 iThome 鐵人賽

DAY 12
1
Software Development

轉職仔之Data Science and ai master後的持續精進技術之路系列 第 12

Binary Search 8 again review code contain & 周一放假但更期待收到錢錢的那一刻XD

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20250926/2017794423geyVPMeO.jpg

https://ithelp.ithome.com.tw/upload/images/20250926/20177944AYJOeE3Cfl.jpg

#include <vector>//動態陣列容器(承載weights)
using namespace std;//省略 std::
//可行性檢查:容量C,在days內、序n件a[0..n-1]運完
static inline bool feasible(const int* a,int n,int days,int C){ //編譯器內聯
    int need=1,cur=0;//need=已用天,cur=當天已裝總重
    for(int i=0;i<n;++i)//裝船到n-1
        int x=a[i];//第i重x
        if(cur+x>C){//x當天(cur)超容量C
            if(++need>days) return false;//隔天need++但若超days end
            cur=x;//新的一天從x開始
        }else{
            cur+=x;//否則同天疊重
        }
    }
    return true;//迴end<days,C容量ok
}

class Solution{
public:
    int shipWithinDays(vector<int>& w,int days){//回最小可容,在days內序運完w
        const int n=(int)w.size();//n=包裹數;例:w=[1,2] 則 n=2
        const int* a=w.data();//底層連續陣列指標
        int L=0,S=0;//L=容量下界初值(等會更新為max)、S=總重(容量上界)
        for(int i=0;i<n;++i){//單次掃描同時最重與總和
            int x=a[i];//當前包裹重
            if(x>L) L=x;//更新下界:至少最重
            S+=x;//更新上界:全容量總和
        }
        int R=S;//容量上界R設為S
        if(days==1||days==n){//
            return days==1?R:L;//days=1→全運;days=n,需容量=最重 L
        }

        while(L<R){//二分搜尋最小可行容量
            int m=(L+R)/2;//取中點容量m(limit check ok
            if(feasible(a,n,days,m)) R=m;//m可行,收右界到m;區間成 [L,32]
            else L=m+1;//若m不可,左界m+1
        }
        return L;//迴endL==R,最小可行容量;
    }
};

真的不能衝太快要好好複習


上一篇
Binary Search 8 & 有咳嗽早點好的方法嗎QQ
系列文
轉職仔之Data Science and ai master後的持續精進技術之路12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
AndyAWD
iT邦新手 2 級 ‧ 2025-09-26 23:14:35

好耶,準備領錢囉

我要留言

立即登入留言